<script lang="ts" setup>
import PictureUpload from "@/components/PictureUpload.vue";
import UrlPictureUpload from "@/components/UrlPictureUpload.vue";
import {computed, onMounted, reactive, ref} from "vue";
import { message } from "ant-design-vue";
import { editPictureUsingPost, getPictureVoByIdUsingGet, listPictureTagCategoryUsingGet } from "@/api/pictureController";
import { useRoute, useRouter } from "vue-router";

type UploadType = 'file' | 'url';

const router = useRouter();
const route = useRoute();
const uploadType = ref<UploadType>('file');
const picture = ref<API.PictureVO>();
const pictureForm = reactive<API.PictureEditRequest>({});
const categoryOptions = ref<string[]>([]);
const tagOptions = ref<string[]>([]);
const formVisible = ref(false);

// 上传成功处理
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture;
  Object.assign(pictureForm, {
    name: newPicture.name,
    introduction: newPicture.introduction,
    category: newPicture.category,
    tags: newPicture.tags
  });
  formVisible.value = true;
  message.success('图片上传成功！');
};
const spaceId = computed(() => route.query?.spaceId)
// 表单提交
const handleSubmit = async (values: any) => {
  if (!picture.value?.id) return;

  try {
    const res = await editPictureUsingPost({
      id: picture.value.id,
      spaceId: spaceId.value,
      ...values,
    });

    if (res.data.code === 0 && res.data.data) {
      message.success('发布成功');
      router.push({ path: `/picture/${picture.value.id}` });
    } else {
      message.error(res.data.message || '发布失败');
    }
  } catch (e: any) {
    message.error(`发布失败: ${e.message}`);
  }
};

// 获取标签分类
const getTagCategoryOptions = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet();
    if (res.data.code === 0 && res.data.data) {
      tagOptions.value = res.data.data.tagList || [];
      categoryOptions.value = res.data.data.categoryList || [];
    }
  } catch (e) {
    message.error('获取分类标签失败');
  }
};

// 获取已有图片数据
const getOldPicture = async () => {
  const id = route.query?.id;
  if (!id) return;

  try {
    const res = await getPictureVoByIdUsingGet({ id });
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data;
      picture.value = data;
      Object.assign(pictureForm, {
        name: data.name,
        introduction: data.introduction,
        category: data.category,
        tags: data.tags
      });
      formVisible.value = true;
    }
  } catch (e) {
    message.error('获取图片数据失败');
  }
};

// 初始化
onMounted(() => {
  getTagCategoryOptions();
  getOldPicture();
});
</script>

<template>
  <div class="upload-container" :class="{ 'has-picture': picture }">
    <div class="upload-wrapper">
      <div class="header-glow"></div>

      <h2 class="upload-title">
        <span class="title-gradient">
          {{ route.query?.id ? '📷 图片美化中心' : '📷 图片创作中心' }}
        </span>
      </h2>
      <div class="upload-mode-switch">
        <button
            class="mode-button"
            :class="{ active: uploadType === 'file' }"
            @click="uploadType = 'file'"
        >
          <span class="icon">📁</span>
          文件上传
        </button>
        <button
            class="mode-button"
            :class="{ active: uploadType === 'url' }"
            @click="uploadType = 'url'"
        >
          <span class="icon">🌐</span>
          URL上传
        </button>
        <span v-if="spaceId" @click="router.push(`/space/${spaceId}`)">上传至空间：{{spaceId}}</span>
      </div>

      <div class="upload-component-wrapper">
        <transition name="fade-mode" mode="out-in">
          <component
              :is="uploadType === 'file' ? PictureUpload : UrlPictureUpload"
              :key="uploadType"
              :spaceId="spaceId"
              :picture="picture"
              :onSuccess="onSuccess"
              class="custom-uploader"
          />
        </transition>
      </div>

      <transition name="form-slide">
        <a-form
            :model="pictureForm"
            class="creative-form"
            @finish="handleSubmit"
        >
          <div class="form-grid">
            <a-form-item name="name" class="form-item glow-item">
              <a-input
                  v-model:value="pictureForm.name"
                  placeholder="作品名称"
                  class="neon-input"
              >
                <template #prefix>
                  <div class="input-icon-wrapper">
                    <svg class="icon" viewBox="0 0 24 24">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
                      <path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
                    </svg>
                  </div>
                </template>
              </a-input>
            </a-form-item>

            <a-form-item name="introduction" class="form-item glow-item">
              <a-textarea
                  v-model:value="pictureForm.introduction"
                  placeholder="作品背后的故事..."
                  class="neon-textarea"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
              />
            </a-form-item>

            <a-form-item label="分类" class="form-item category-item">
              <a-auto-complete
                  v-model:value="pictureForm.category"
                  placeholder="选择分类"
                  :options="categoryOptions"
                  class="neon-select"
              >
                <template #suffixIcon>
                  <div class="select-icon">
                    <svg class="icon" viewBox="0 0 24 24">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-2-3h4v2h-4zm1-6h2v4h-2z"/>
                    </svg>
                  </div>
                </template>
              </a-auto-complete>
            </a-form-item>

            <a-form-item label="标签" class="form-item tags-item">
              <a-select
                  v-model:value="pictureForm.tags"
                  mode="tags"
                  placeholder="添加标签"
                  :options="tagOptions"
                  class="neon-tags"
              >
                <template #suffixIcon>
                  <div class="tag-icon">
                    <svg class="icon" viewBox="0 0 24 24">
                      <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/>
                      <path d="M8 14h8v2H8z"/>
                    </svg>
                  </div>
                </template>
              </a-select>
            </a-form-item>

            <a-form-item class="submit-item">
              <button class="creative-btn" type="submit">
                <span class="btn-text">发布作品</span>
                <div class="hover-effect"></div>
              </button>
            </a-form-item>
          </div>
        </a-form>
      </transition>

      <div class="upload-tips">
        <span class="hotkey-tip">
          ✨ 创作提示：使用逗号分隔多个标签，按 ⌘S 快速保存
        </span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
@keyframes gradientFlow {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.upload-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  padding: 2rem;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(45deg, rgba(99, 102, 241, 0.1) 0%, rgba(165, 180, 252, 0.05) 100%);
    z-index: 0;
  }
}

.upload-wrapper {
  background: rgba(15, 23, 42, 0.9);
  border-radius: 1.5rem;
  padding: 2.5rem;
  box-shadow: 0 0 50px rgba(99, 102, 241, 0.2);
  transition: transform 0.3s ease;
  width: 100%;
  max-width: 800px;
  position: relative;
  backdrop-filter: blur(12px);
  border: 1px solid rgba(99, 102, 241, 0.3);
}

.header-glow {
  position: absolute;
  top: -100px;
  left: 50%;
  width: 200%;
  height: 200px;
  background: radial-gradient(circle, rgba(99, 102, 241, 0.2) 0%, transparent 70%);
  transform: translateX(-50%);
  z-index: -1;
}

.upload-title {
  text-align: center;
  margin-bottom: 2rem;
  position: relative;

  .title-gradient {
    background: linear-gradient(45deg, #818cf8 30%, #c4b5fd 70%);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    font-size: 2.2rem;
    font-weight: 700;
    letter-spacing: 1px;
  }
}

.upload-mode-switch {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin: 2rem 0;

  .mode-button {
    padding: 0.8rem 1.5rem;
    border: none;
    border-radius: 8px;
    background: rgba(99, 102, 241, 0.1);
    color: #818cf8;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 500;

    &:hover {
      background: rgba(99, 102, 241, 0.2);
      transform: translateY(-2px);
    }

    &.active {
      background: linear-gradient(45deg, #6366f1, #8b5cf6);
      color: white;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
  }
}

.upload-component-wrapper {
  margin: 2rem 0;
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.creative-form {
  margin-top: 2rem;
  position: relative;
  z-index: 10;
  background: rgba(15, 23, 42, 0.9);
  padding: 1.5rem;
  border-radius: 12px;
  border: 1px solid rgba(99, 102, 241, 0.3);
  box-shadow: 0 0 20px rgba(99, 102, 241, 0.1);

  .form-grid {
    display: grid;
    gap: 1.5rem;
  }
}

.neon-input,
.neon-textarea,
.neon-select,
.neon-tags {
  background: rgba(30, 41, 59, 0.7) !important;
  border: 1px solid rgba(99, 102, 241, 0.3) !important;
  border-radius: 12px !important;
  color: #e2e8f0 !important;
  transition: all 0.3s ease;

  &:hover {
    border-color: #818cf8 !important;
    box-shadow: 0 0 12px rgba(129, 140, 248, 0.2) !important;
  }

  &:focus {
    box-shadow: 0 0 20px rgba(129, 140, 248, 0.3) !important;
  }
}

.creative-btn {
  position: relative;
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  padding: 1rem 2.5rem;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  width: 100%;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;

  .btn-text {
    position: relative;
    z-index: 2;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(99, 102, 241, 0.4);
  }
}

.fade-mode-enter-active,
.fade-mode-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.fade-mode-enter-from,
.fade-mode-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.form-slide-enter-active,
.form-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.form-slide-enter-from,
.form-slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.upload-tips {
  text-align: center;
  margin-top: 2rem;
  color: #64748b;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .upload-wrapper {
    padding: 1.5rem;
    margin: 1rem;
  }

  .upload-title .title-gradient {
    font-size: 1.8rem;
  }

  .upload-mode-switch {
    flex-direction: column;

    .mode-button {
      width: 100%;
      justify-content: center;
    }
  }

  .creative-form {
    padding: 1rem;
  }
}
</style>
